﻿using Microsoft.EntityFrameworkCore;
using System;
using WidgetsDesign.API.DataBase;
using WidgetsDesign.API.Models;

namespace WidgetsDesign.API.Services
{
    public class HitokotoRepository : IHitokotoRepository
    {
        private readonly AppDbContext _context;
        public HitokotoRepository(AppDbContext context)
        {
            _context = context;
        }
        public async Task<HitokotoModel?> GetHitokotoAsync(string[] types, int MaxSize, int MinSize)
        {
            var query = from h in _context.Hitokoto
                        where types.Contains(h.Type) && h.Length >= MinSize && h.Length <= MaxSize
                        select h;
            var filteredData = await query.ToListAsync();
            if (filteredData.Count == 0)
            {
                return null;
            }
            var random = new Random();
            var fist1 =  filteredData[random.Next(filteredData.Count)];
            return fist1;
        }
        public async Task<bool> GetHitokotoExistsAsync(int HitokotoId)
        {
            return await _context.Hitokoto.AnyAsync(t => t.Id == HitokotoId);
        }
        public void CreateHitokoto(HitokotoModel Hitokoto)
        {
            if (Hitokoto == null)
            {
                throw new ArgumentNullException(nameof(Hitokoto));
            }
            _context.Hitokoto.Add(Hitokoto);
        }
        public async Task<bool> SaveAsync()
        {
            return (await _context.SaveChangesAsync() >= 0);
        }
    }
}
